package com.ys.web.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.ys.WebConstants;
import com.ys.extend.utils.CommonUtils;
import com.ys.extend.utils.ContextHolderUtils;
import com.ys.extend.utils.LogUtil;
import com.ys.extend.utils.TimeUtil;
import com.ys.web.entity.User;
import com.ys.web.pojo.MenuInfo;
import com.ys.web.pojo.MenuModule;
import com.ys.web.pojo.SystemPermissonInfo;
import com.ys.web.security.SystemPermissionUtils;
import com.ys.web.service.CompanyService;
import com.ys.web.service.SystemService;
import com.ys.web.service.UserService;

@Controller
public class SystemController {

	@Autowired
	UserService userService;
	
	@Autowired
	SystemService systemService;
	
	@Autowired
	CompanyService companyService;
	@RequestMapping(value="checkUser.do",method=RequestMethod.POST)
	@ResponseBody
	public String checkUser(HttpServletRequest request){
		String username=request.getParameter("username");
		String password = request.getParameter("password");
		username = username.trim();
		password = password.trim();
		if(username==null||"".equals(username)||password==null||"".equals(password)){
			return "请输入用户名和密码";
		}
		
		if(username.length()>8){
			return "用户名不能超过8个字符";
		}
		
		if(password.length()<6||password.length()>16){
			return "密码不能超过16个字符或少于6个字符";
		}
			User user;
			try {
				user = userService.getUserByUsername(username);
				if(user==null){
					return "你输入的用户不存在";
				}else if(!password.equals(user.getPassword())){
					return "你输入的密码不正确";
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return "系统异常";
			}
		HttpSession session = request.getSession();
		//添加系统信息
		systemService.addSystemUserInfo(session, user);
	
		return WebConstants.SUCCESS_CODE;
	}
	
	/**
	 * 获取菜单
	 * @param request
	 * @param response
	 */
	@RequestMapping(value="getMenu.do",method=RequestMethod.GET)
	public void getMenu(HttpServletRequest request,HttpServletResponse response){
		try {
			String username = ContextHolderUtils.getSessionUsername();
			List<MenuModule> menuModules = SystemPermissionUtils.getUserPermission(username).getMenuModules();
			response.setContentType("text/html;charset=UTF-8");
			PrintWriter pw = response.getWriter();
			StringBuffer menuBuffer = new StringBuffer("<ul class=\"layui-nav layui-nav-tree site-demo-nav\">");
			
			if(menuModules!=null){
				for(MenuModule menuModule:menuModules){
					menuBuffer.append(" <li class=\"layui-nav-item \">");
					menuBuffer.append("<a class=\"javascript:;\" href=\"javascript:;\">");
					//System.out.println(menuModule.getModule());
					menuBuffer.append(menuModule.getModule());
					menuBuffer.append("</a>");
					menuBuffer.append("<span class=\"layui-nav-more\"></span></a>");
					List<MenuInfo> menuInfos = menuModule.getMenuList();
					menuBuffer.append("<dl class=\"layui-nav-child \" >");
					for(MenuInfo menuInfo:menuInfos){
						menuBuffer.append("<dd>");
						menuBuffer.append("<a href=\""+request.getContextPath()+"/"+menuInfo.getUrl()+"\">");
						menuBuffer.append(menuInfo.getName());
						menuBuffer.append("</a>");
						menuBuffer.append("</dd>");
						
					}
					menuBuffer.append("</dl>");
					menuBuffer.append("</li>");
				}
				
				
			}
			
			menuBuffer.append("</ul>");
			//System.out.println(menuBuffer.toString());
			pw.println(menuBuffer.toString());
			pw.flush();
			pw.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			
		}
	}
	
	@RequestMapping(value="userIndex.do")
	public ModelAndView userIndex(HttpServletRequest request){
		HttpSession session = request.getSession();
		String username=(String) session.getAttribute("username");
		SystemPermissonInfo systemPermissonInfo = SystemPermissionUtils.getUserPermission(username);
		
		//登录日志
		StringBuilder log = new StringBuilder();
		log.append("KAD_logs,UserName:").append(username)
		   .append(",IP:").append(CommonUtils.getRemoteIp(request))
		   .append(",Time:").append(TimeUtil.getFormatDate(new Date(), "yyyy-MM-dd_HH:mm:ss"));
		LogUtil.info(log.toString());
		
		if(systemPermissonInfo!=null){
			Set<Integer> roleSet = systemPermissonInfo.getRoleId();	
	//		System.out.println("roleSet--"+roleSet);
			if(roleSet!=null){
				if(roleSet.contains(WebConstants.SUPER_USER)){
					//超级管理员显示用户列表
					return new ModelAndView("redirect:/userController.do?showUser");
				}else if(roleSet.contains(WebConstants.SEM_MANAGER_USER)){
					//sem经理显示所有sem经理导入的数据
					return new ModelAndView("redirect:/companyController.do?showManageCompany");
				}else if(roleSet.contains(WebConstants.SEM_USER)){
					//sem显示导入界面
					return new ModelAndView("redirect:/companyController.do?showSemCompany");
				}
			}		
		}
		//显示无效页面
		return new ModelAndView("/login/login");
							
	}
	
	@RequestMapping(value="logout.do")
	public ModelAndView logout(HttpServletRequest request){
		HttpSession session = request.getSession();
		String username= (String)session.getAttribute("username");
		session.removeAttribute("username");
		session.removeAttribute("userId");
		SystemPermissionUtils.removeUserPermission(username);
		return new ModelAndView("/login/login");
		
	}
	
	@RequestMapping(value="index.do")
	public ModelAndView login(HttpServletRequest request){
		return new ModelAndView("/login/login");
	}
	
	
	
}
